<?php
//发表文章权限
if ((isset($_GET['anhao']) ? $_GET['anhao'] : "") != "zhimakaimen") die("Authorized Personnel Only!");

require_once 'base.php';

$tpl = new Template('t');
$tpl->setFile ( "main", "main.html" );
$tpl->setFile ( "publication", "publication.html" );

$db = conn();

// ------------- 页面基本信息 -------------
// 分类
$category_str = '';
foreach ($CFG['category'] as $key => $category){
	$category_str .= "<li class=\"cat-item\"><a href=\"index.php?search=category&category={$key}\" title=\"查看所有分类为 {$category} 的文章\">{$category}</a></li>";
}
// 标签
$sql_tags = "SELECT * FROM tags ORDER BY amount DESC LIMIT 25";
$rs=$db->query($sql_tags, MYSQL_ASSOC);
$tag_str = '';
foreach($rs as $tag){
    $tag['name'] = stripslashes($tag['name']);
	$tag_str .= "<a href=\"index.php?search=tag&tag={$tag['name']}\" title=\"查看所有标记为 {$tag['name']} 的文章\">{$tag['name']}</a> ";
}
// 显示
$tpl->setVar(array(
    'website_url' => $CFG['website']['url'],
    'web_title' => $CFG['website']['page_title'],
	'description' => $CFG['website']['description'],
	'category_str' => $category_str,
	'tag_str' => $tag_str
));
// ------------- end 页面基本信息 -------------

$tpl->setVar('page_title', "添加/修改博文 - " . $CFG['website']['page_title']); // 页面title

// ------------- 添加、修改文章 -------------
if (pm() == "GET"){
	$aid = del_space(fget('id', 0));
	if ($aid){ // 读取文章
		$sql = "SELECT * FROM article WHERE aid='{$aid}'";
		$rs=$db->query($sql, MYSQL_ASSOC);
		if(!empty($rs)){
			foreach($rs as $v){
				$tpl->setVar(array(
					"aid" => $v['aid'],
					"post_title" => stripslashes($v['title']),
					"post_headline" => stripslashes($v['headline']),
					"post_content" => stripslashes($v['contents']),
					"category" => show_category($CFG['category'], $v['category']),
					"tags" => stripslashes($v['tags'])
				));
			}
		}else{ // 读取文章失败
			$tpl->setVar("msg", "读取文章失败，请添加新文章！");
		}
	}else{ // 新加文章
		$tpl->setVar(array(
			"category" => show_category($CFG['category'])
		));
	}
	// 服务器时间
	$tpl->setVar(array(
		"display_time" => date("Y年n月j日 G:i"),
		"timestamp" => time() * 1000
	));
}else{ // 接收post数据，处理入库
	$aid = del_space(fpost('id', 0));
	$title = addslashes(trim(fpost('post_title')));
	$headline = addslashes(fpost('post_headline'));
	$contents = addslashes(fpost('post_content'));
	$category = fpost('category');
	$tags = addslashes(trim(fpost('tags')));
	$tags_old = addslashes(trim(fpost('tags_old')));
	$submit_time = time();

	// 验证数据合法性
	if ($title == ''){
		die("标题不能为空，请<a href=\"javascripe: history.back();\">返回</a>重试！");
	}else if (strlen_utf8($title) > 100){
		die("标题最多不得超过100个字符，请<a href=\"javascripe: history.back();\">返回</a>重试！");
	}
	if ($headline == ''){
		die("摘要内容不能为空，请<a href=\"javascripe: history.back();\">返回</a>重试！");
	}else if (strlen_utf8($headline) > 1000){
		die("摘要内容最多不得超过1000个字符，请<a href=\"javascripe: history.back();\">返回</a>重试！");
	}
	if ($contents == ''){
		die("内容不能为空，请<a href=\"javascripe: history.back();\">返回</a>重试！");
	}
	if (!$category){
		die("没有选择分类，请<a href=\"javascripe: history.back();\">返回</a>重试！");
	}
	if ($tags != ''){
		if (strlen_utf8($tags) > 100){
			die("标签最多不得超过100个字符，请<a href=\"javascripe: history.back();\">返回</a>重试！");
		}
	}
	// ----- -----

	if ($aid){ // 修改
		$sql_update = "UPDATE article SET title='{$title}', headline='{$headline}', contents='{$contents}', category={$category}, tags='{$tags}', update_time={$submit_time} WHERE aid='{$aid}'";
		if ($db->query($sql_update)){
			if ($tags_old != $tags){ // tag有改动，更新数据库
				$tag_arr = explode(",", $tags);
				$tag_old_arr = explode(",", $tags_old);
				$same_num = 0;
				$sql_tags_insert = "INSERT INTO tags (name) values";
				$insert_tag_sign = 0;
				$tags_for_log = "";
				foreach ($tag_arr as $tag){ // tags表添加新加的tag
					$tag = trim($tag);
					foreach ($tag_old_arr as $tag_old){
						$tag_old = trim($tag_old);
						if ($tag == $tag_old){
							$same_num = 1;
							break;
						}
					}
					if (!$same_num){ // 新添加的标签，更新数据库
						$sql_tags_insert = "UPDATE tags SET amount=amount+1 where name='{$tag}'";
						if ($db->query($sql_tags_insert)){
							if (!$db->processNum()){ // 更新条目为0时，说明此标签不存在，组织插入新标签的sql语句
								$sql_tags_insert .= "('{$tag}'), ";
								$insert_tag_sign = 1;
								$tags_for_log .= $tag . ",";
							}
						}else{
							error_logs("log/tag_err.txt", date("Y-m-d H:i:s") . " - 标签“{$tag}”的数目更新失败！\n\r");
						}
					}
				}
				if ($insert_tag_sign){
					$sql_tags_insert = substr($sql_tags_insert, 0, -2);
					if (!$db->query($sql_tags_insert)){
						$tags_for_log = substr($tags_for_log, 0, -1);
						error_logs("log/tag_err.txt", date("Y-m-d H:i:s") . " - 标签“{$tags_for_log}”插入失败！\n\r");
					}
				}

				foreach ($tag_old_arr as $tag_old){ // tags表删除旧的tag
					$tag_old = trim($tag_old);
					foreach ($tag_arr as $tag){
						$tag = trim($tag);
						if ($tag == $tag_old){
							$same_num = 1;
							break;
						}
					}
					if (!$same_num){ // 删除旧的标签，更新数据库
						$sql_tags_update = "UPDATE tags SET amount=amount-1 where name='{$tag_old}'";
						if (!$db->query($sql_tags_update)){
							error_logs("log/tag_err.txt", date("Y-m-d H:i:s") . " - 标签“{$tag_old}”的数目减少时更新失败！\n\r");
						}
					}
				}
			}

			echo "<script>alert('文章修改成功！');window.location.href=\"viewblog.php?id={$aid}\";</script>";
		}else{
            error_logs("log/article_post_err.txt", date("Y-m-d H:i:s") . " - 修改文章“{$title}”失败！\n\r");
        }
	}else{ // 添加
		$aid = generate_id();
        $submit_ip = ip2long(getip());
        $submit_ip = $submit_ip ? $submit_ip : 0;
		$sql_article_insert = "INSERT INTO article (aid, title, headline, contents, category, tags, submit_time, submit_ip) VALUES('{$aid}', '{$title}', '{$headline}', '{$contents}', {$category}, '{$tags}', {$submit_time}, {$submit_ip})";
		if ($db->query($sql_article_insert)){ // 添加成功
			// 添加tag表统计数据
			$tag_arr = explode(",", $tags);
            $sql_tags_insert = "INSERT INTO tags (name) values";
            $insert_tag_sign = 0;
            $tags_for_log = "";
            foreach ($tag_arr as $tag){
                $tag = trim($tag);
                if (!empty($tag)){
                    $sql_tags_update = "UPDATE tags SET amount=amount+1 where name='{$tag}'";
                    if ($db->query($sql_tags_update)){
                        if (!$db->processNum()){ // 更新条目为0时，说明此标签不存在，组织插入新标签的sql语句
                            $sql_tags_insert .= "('{$tag}'), ";
                            $insert_tag_sign = 1;
                            $tags_for_log .= $tag . ",";
                        }
                    }else{
                        error_logs("log/tag_err.txt", date("Y-m-d H:i:s") . " - 标签“{$tag}”的数目更新失败！\n\r");
                    }
                }
            }
            if ($insert_tag_sign){
                $sql_tags_insert = substr($sql_tags_insert, 0, -2);
                if (!$db->query($sql_tags_insert)){
                    $tags_for_log = substr($tags_for_log, 0, -1);
                    error_logs("log/tag_err.txt", date("Y-m-d H:i:s") . " - 标签“{$tags_for_log}”插入失败！\n\r");
                }
            }

			echo "<script>alert('文章添加成功！'); window.location.href=\"viewblog.php?id={$aid}\";</script>";
		}else{
			// 添加失败，待处理
            error_logs("log/article_err.txt", date("Y-m-d H:i:s") . " - 发表文章“{$title}”失败！\n\r");
		}
	}
}

$db->close();

$tpl->parse('main_content', 'publication');
$tpl->p("main");
?>